//index.js
var util = require('../../utils/util.js');
var qcloud = require('../../vendor/wafer2-client-sdk/index');
var config = require('../../config');
Page({
  data: {
    userInfo: {},
    // 用户信息已登录
    userInfoLogged: {},
    // 进行中订单数量
    orderingNum: 0,
    orderInfo: {},
    markers: [],
    logged: false,
    takeSession: false,
    isOpening:0,
    isCloseding:0,
    requestResult: '',
    // hasOrderUnderway: "0",
    type: 'customer',
    scale: 18, // 缩放级别，默认18，数值在0~18之间
    latitude: 31.681004, // 给个默认值,
    longitude: 120.321466 // 给个默认值 江苏无锡OPARK 纬度:31.681004 经度:120.321466
  },

  // 用户登录示例
  onLoad: function (options) {
    // wx.clearStorage();
    if (this.data.logged) return
    // util.showBusy('正在登录')
    var that = this
    // 检测本地数据，是否有正在召唤中的快递单
    // 获取本地数据-用户信息
    wx.getStorage({
      key: 'orderStatus',
      // 能获取到则显示用户信息，并保持登录状态，不能就什么也不做
      success: (json) => {
        that.setData({
          // 当前订单状态
          // hasOrderUnderway: "1",
          orderStatus: json.data.orderStatus
        })
        console.log(this.data.orderStatus.msg);
      },
      fail: function () {
        that.setData({
          // 当前订单状态
          orderStatus: "0"
        })
      }
    });
    wx.request({
      url: 'https://boxapi.supergk.com/server/box/all_stake_list',
      data: {},
      method: 'GET',
      success: (res) => {
        // console.log(res.data.data.all_stake_list)
        var _marks = res.data.data.all_stake_list;
        _marks = _marks.map(function (m) {
          // m.title = m.name;
          m.iconPath = "../../images/but_mapbox.png";
          m.width = 45;
          m.height = 50;
          return m;
        });

        this.setData({
          markers: _marks
        })
      }
    })

    // 调用登录接口
    qcloud.login({
      success(result) {
        if (result) {
          console.log(result + "登陆接口login");
          console.log(result);
          //首次登录，返回用户信息，不请求用户信息接口获取信息
          // util.showSuccess('登录成功1')================
          var userId = result.uid;
          that.setData({
            userInfo: result,
            logged: true
          })
          // 存储用户信息到本地
          wx.setStorage({
            key: 'userInfo',
            data: {
              userInfo: result,
              bType: "warn",
              actionText: "退出登录"
            },
            success: function (res) {
              console.log("存储成功2")
            },
          })
          getUserInfo(userId)

           // 轮询 是否有待结束订单
          that.requestSetMyRecipient();
          setInterval((function callback() {
            that.requestSetMyRecipient();
            getUserInfo(userId)
          }).bind(this), 5000);

        } else {
          // 如果不是首次登录，不会返回用户信息，请求用户信息接口获取
          qcloud.request({
            url: config.service.requestUrl,//server/user?type=customer
            method: "GET",
            login: true,
            success(result) {
              console.log(result);
              console.log(result + "走用户信息接口");
              console.log('请求用户信息接口成功2');
              if (result.data.code == 0) {
                var userId = result.data.data.uid;
                // util.showSuccess('登录成功2')=======================
                that.setData({
                  userInfo: result.data.data,
                  logged: true
                })
                // 存储用户信息到本地
                wx.setStorage({
                  key: 'userInfo',
                  data: {
                    userInfo: result.data.data,
                    bType: "warn",
                    actionText: "退出登录"
                  },
                  success: function (res) {
                    // console.log("存储成功2")
                  },
                })
                getUserInfo(userId)
                // 轮询 是否有待结束订单
                that.requestSetMyRecipient();
                setInterval((function callback() {
                  that.requestSetMyRecipient();
                  getUserInfo(userId)
                }).bind(this), 5000);

              } else {
                console.log(result.data.msg);
              }
            },
            fail(error) {
              console.log('请求用户信息接口失败');
              util.showModel('请求失败', error)
              console.log('request fail', error)
            }
          })
        }
      },
      fail(error) {
        util.showModel('登录失败', error)
        console.log('登录失败', error)
      }
    })

    // 获取进行中订单，获取 是否有进行中订单
    function getUserInfo(userId) {
      //获取正在进行中的订单个数
      const requestorderingNum = wx.request({
        url: 'https://boxapi.supergk.com/server/order/query_going_order_count',
        data: {
          uid: userId
        },
        header: {
          'content-type': 'application/json'
        },
        method: "GET",
        success: function (res) {
          if (res.data.code == "0") {
            that.setData({
              orderingNum: res.data.data.count,
            })
          } else {
            console.log();
          }
        }
      })//获取正在进行中的订单个数 結束

      //  获取是否有进行中的订单
      const requestCallCourier = wx.request({
        url: "https://boxapi.supergk.com/server/user/call_courier",
        data: util.json2Form({ uid: userId, type: "1", address_id: "", box_list: "" }),
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function (res) {
          if (res.data.code == 0) {
            console.log(res.data)
            // res.data.data.state  
            //   状态：1 尚未生成单子
            //        2 生成单子无人接单 
            //        3 有人接单
            //        4 快递员申请结束服务 
            that.setData({
              orderStatus: res.data
            })
            
          }
        }
      })

      //获取用户信息
      const requestUser = wx.request({
        url: 'https://boxapi.supergk.com/server/user/user_info',
        data: {
          uid: userId,
        },
        header: {
          'content-type': 'application/json'
        },
        method: "GET",
        success: function (res) {
          if (res.data.code == "0") {
            that.setData({
              userInfoLogged: res.data.data,
            })
            // 存储用户信息到本地
            wx.setStorage({
              key: 'userInfoLogged',
              data: {
                userInfoLogged: res.data.data,
              },
              success: function (res) {
                console.log("存储用户信息成功+user_info")
              },
            })
          } else {
            console.log(res.data.msg);
          }
        }
      })//获取用户信息 結束

    }


    // 1.页面初始化 options为页面跳转所带来的参数
    // 1.获取定时器，用于判断是否已经在计费
    // this.timer = options.timer;
    // 2.调用wx.getLocation系统API,获取并设置当前位置经纬度
    wx.getLocation({
      type: "gcj02", // 坐标系类型
      // 获取经纬度成功回调
      success: (res) => { // es6 箭头函数，可以解绑当前作用域的this指向，使得下面的this可以绑定到Page对象
        this.setData({  // 为data对象里定义的经纬度默认值设置成获取到的真实经纬度，这样就可以在地图上显示我们的真实位置
          longitude: res.longitude,
          latitude: res.latitude
        })
      }
    });
    // 3.设置地图控件的位置及大小，通过设备宽高定位
    wx.getSystemInfo({ // 系统API,获取系统信息，比如设备宽高
      success: (res) => {
        this.setData({
          // 定义控件数组，可以在data对象初始化为[],也可以不初始化，取决于是否需要更好的阅读
          controls: [{
            id: 1, // 给控件定义唯一id
            iconPath: '/images/location.png', // 控件图标
            position: { // 控件位置
              left: 20, // 单位px
              top: res.windowHeight - 200, // 根据设备高度设置top值，可以做到在不同设备上效果一致
              width: 50, // 控件宽度/px
              height: 50 // 控件高度/px
            },
            clickable: true // 是否可点击，默认为true,可点击
          },
          {
            id: 2,
            iconPath: '/images/use.png',
            position: {
              left: res.windowWidth / 2 - 88,
              top: res.windowHeight - 205,
              width: 176,
              height: 55
            },
            clickable: true
          },
          {
            id: 3,
            iconPath: '/images/warn.png',
            position: {
              left: res.windowWidth - 70,
              top: res.windowHeight - 200,
              width: 50,
              height: 50
            },
            clickable: true
          },
          {
            id: 4,
            iconPath: '/images/marker.png',
            position: {
              left: res.windowWidth / 2 - 11,
              top: res.windowHeight / 2 - 100,
              width: 22,
              height: 45
            },
            clickable: false
          },
          {
            id: 5,
            iconPath: '/images/avatar.png',
            position: {
              left: res.windowWidth - 68,
              top: res.windowHeight - 275,
              width: 45,
              height: 45
            },
            clickable: true
          }]
        })
      }
    });
  },

  // 地图控件点击事件
  bindcontroltap: function (e) {
    // 判断点击的是哪个控件 e.controlId的值是当前点击控件的id。
    switch (e.controlId) {
      // 点击定位控件
      case 1: this.movetoPosition();
        break;
      // 点击立即用箱子，判断当前是否正在计费，此处只需要知道是调用扫码，后面会讲到这里的判断条件
      case 2: {
        var depositState = wx.getStorageSync("userInfo").userInfo.deposit;
        var userId = wx.getStorageSync("userInfo").userInfo.uid;
        var _uid = wx.getStorageSync("userInfo").userInfo.uid;
        var that = this;
        if (depositState == 1) {
          wx.scanCode({
            success: (res) => {
              var _box_bn = res.result;
              // 正在获取密码通知
              // wx.showToast({
              //   title: '扫码成功',
              //   icon: "success"
              // })
                         
              // 扫码获取 箱子编号后，请求接口，获取接口参数
              wx.request({
                url: 'https://boxapi.supergk.com/server/user/user_sm',
                header: {
                  "Content-Type": "application/x-www-form-urlencoded"
                },
                data: util.json2Form({ user_id: _uid, box_bn: _box_bn }),
                // data: { user_id: user_id, box_bn: box_bn},
                method: 'POST',
                success: function (e) {
                  console.log(e)
                  if (e.data.code == 0) {
                    var _call_back_code = e.data.data.call_back_code;
                    if (_call_back_code == 1) {
                      that.userOpenBox(_box_bn);
                    } else if (_call_back_code == 2) {
                      that.userOpenBoxNow(_box_bn);
                    } else if (_call_back_code == 3) {
                      that.receiverOpenBox(_box_bn);
                    }
                  } else {
                    console.log(e.data.msg)
                    wx.showModal({
                      title: '开箱失败',
                      content: e.data.msg,
                      showCancel: false
                    })
                  }
                }
              })
              // 请求结束
            },
            fail: (res) => {
              wx.showToast({
                title: '失败',
                icon: 'success',
                duration: 2000
              })
            },
            complete: (res) => {
            }

          })
        } else {
          wx.navigateTo({
            url: '../wallet/wallet'
          });
        }

      }
        break;
      // 点击保障控件，跳转到报障页
      case 3: wx.navigateTo({
        url: '../message/message'
      });
        break;
      // 点击头像控件，跳转到个人中心
      case 5: wx.navigateTo({
        url: '../my/my'
      });
        break;
      default: break;
    }
  },


  //1、 用户扫码开箱（直接生成订单）
  userOpenBox: function (_box_bn) {
    var that = this;
    var _uid = wx.getStorageSync("userInfo").userInfo.uid;
    const requestGetRequestUrl = wx.request({
      url: "https://boxapi.supergk.com/server/box/user_open_box",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      data: util.json2Form({
        user_id: _uid,
        box_bn: _box_bn
      }),
      success: function (result) {
        console.log(result)
        if (result.data.code == 0) {
          console.log(" 用户扫码开箱（直接生成订单，返回箱子id）");
          console.log(" 用户扫码开箱（检测箱子打开状态，打开后生成订单，直接生成订单）");
          //  跳转到扫码结果页(携带 箱子id 和箱子编号)
          wx.redirectTo({
            url: '../scanresult/scanresult?box_bn=' + _box_bn + '&box_id=' + result.data.data.box_id,
          })  
       
        } else {
          console.log(result.data.msg)
          wx.showModal({
            title: '开箱失败',
            content: result.data.msg,
            showCancel: false
          })
        }
      }
    })
  },

  //2、 运输途中开箱
  userOpenBoxNow: function (_box_bn) {
    var _uid = wx.getStorageSync("userInfo").userInfo.uid;
    const requestGetRequestUrl = wx.request({
      url: "https://boxapi.supergk.com/server/box/user_open_box_now",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      data: util.json2Form({
        user_id: _uid,
        box_bn: _box_bn
      }),
      success: function (result) {
        console.log(result)
        if (result.data.code == 0) {
          console.log("运输途中开箱");
          console.log(result.data.msg)
          //  跳转到扫码结果页(携带 箱子id 和箱子编号)
          wx.redirectTo({
            url: '../scanresultInWay/scanresultInWay?box_bn=' + _box_bn ,
          })   
          // wx.showToast({
          //   title: result.data.msg,
          //   icon: "success"
          // })
        } else {
          console.log(result.data.msg)
          wx.showModal({
            title: '提示',
            content: result.data.msg,
            showCancel: false
          })
        }
      }
    })
  },

  //3、 接受方扫码开箱(接收方客户扫码开箱，会对扫码对象身份做校验，返回开箱码)
  receiverOpenBox: function (_box_bn) {
    var _uid = wx.getStorageSync("userInfo").userInfo.uid;
    const requestGetRequestUrl = wx.request({
      url: "https://boxapi.supergk.com/server/box/receiver_open_box",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      data: util.json2Form({
        user_id: _uid,
        box_bn: _box_bn
      }),
      success: function (result) {
        console.log(result)
        if (result.data.code == 0) {
          console.log("接受方扫码开箱");
          console.log(result.data.msg)
          wx.redirectTo({
            url: '../scanresultInWay/scanresultInWay?box_bn=' + _box_bn,
          })  
          // wx.showToast({
          //   title: result.data.msg,
          //   icon: "success"
          // })
        } else {
          console.log(result.data.msg)
          wx.showModal({
            title: '提示',
            content: result.data.msg,
            showCancel: false
          })
        }
      }
    })
  },

  // 拖动地图事件
  bindregionchange: function (e) {
    // 拖动地图，获取附件箱子位置
    if (e.type == "begin") {
      wx.request({
        url: 'https://boxapi.supergk.com/server/box/all_stake_list',
        data: {},
        method: 'GET',
        success: (res) => {
          // console.log(res.data.data.all_stake_list)
          var _marks = res.data.data.all_stake_list;

          _marks = _marks.map(function (m) {
            // m.title = m.name;
            m.iconPath = "../../images/but_mapbox.png";
            m.width = 45;
            m.height = 50;
            return m;
          });

          this.setData({
            _markers: _marks
          })
        }
      })
      // 停止拖动，显示箱子位置
    } else if (e.type == "end") {
      this.setData({
        markers: this.data._markers
      })
    }
  },
  // 地图标记点击事件，连接用户位置和点击的箱子位置
  bindmarkertap: function (e) {
    let _markers = this.data.markers; // 拿到标记数组
    let markerId = e.markerId; // 获取点击的标记id
    let currMaker;
    _markers.map(function (m) {
      if (m.id == markerId) {
        currMaker = m;
      }
    });
    console.log(markerId);
    wx.navigateTo({
      url: '../stake/stake?stake_id=' + markerId,
    })

    // 通过id,获取当前点击的标记
    // this.setData({
    //   polyline: [{
    //     points: [{ // 连线起点
    //       longitude: this.data.longitude,
    //       latitude: this.data.latitude
    //     }, { // 连线终点(当前点击的标记)
    //       longitude: currMaker.longitude,
    //       latitude: currMaker.latitude
    //     }],
    //     color: "#FF0000DD", // 连线颜色
    //     width: 1, // 连线宽度
    //     dottedLine: true // 虚线
    //   }],
    //   scale: 18
    // })
  },
  onReady: function () {
    // 页面渲染完成
  },
  // 页面显示
  onShow: function () {
    // 1.创建地图上下文，移动当前位置到地图中心
    this.mapCtx = wx.createMapContext("ofoMap"); // 地图组件的id
    this.movetoPosition()
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  // 定位函数，移动位置到地图中心
  movetoPosition: function () {
    this.mapCtx.moveToLocation();
  },
  // 跳转至欢迎使用
  movetoGetRbox: function () {
    var that = this;
    var _uid = wx.getStorageSync("userInfo").userInfo.uid;
    //  获取是否有进行中的订单
    const requestCallCourier = wx.request({
      url: "https://boxapi.supergk.com/server/user/call_courier",
      data: util.json2Form({ uid: _uid, type: "1", address_id: "", box_list: "" }),
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      success: function (res) {
        if (res.data.code == 0) {
          console.log(res.data)
          // res.data.data.state  
          //   状态：1 尚未生成单子
          //        2 生成单子无人接单 
          //        3 有人接单
          //        4 快递员申请结束服务 
          // console.log(this.data.hasOrderUnderway);
          if (res.data.data.state == "1") {//如果不存在召唤中订单
            // 跳转到地址选择页面
            console.log('不存在召唤中订单');
            wx.navigateTo({
              url: '../my/selectAddress/selectAddress'
            })
          } else {//存在召唤中订单
            console.log('存在召唤中订单');
            wx.showModal({
              title: "提示",
              content: res.data.msg,
              showCancel: false
            })
          }
          that.setData({
            orderStatus: res.data
          })

        }
      }
    })
 
  },

  //取消召唤快递员
  cancelCall: function () {
    var that = this;
    //取消召唤快递员
    const requestUser = wx.request({
      url: 'https://boxapi.supergk.com/server/user/cancel_courier', //取消召唤快递
      // data: {
      //   id: this.data.orderStatus.data.id,
      // },
      data: util.json2Form({ id: this.data.orderStatus.data.id, }),
      header: {
        'Content-type': 'application/x-www-form-urlencoded'
      },
      method: "POST",
      success: function (res) {
        if (res.data.code == "0") {
          util.showSuccess(res.data.msg)
          that.data.orderStatus.data.state = 1
          that.setData({
            // hasOrderUnderway: "0",
            orderStatus: that.data.orderStatus,
          })
          //  清除本地订单信息
          wx.removeStorage({
            key: 'orderStatus',
            success: function (res) {
              console.log("清除本地订单信息成功")
            },
          })
        } else {
          console.log(res.data.msg);
        }
      }
    })//取消召唤快递员 結束
  },

  // 轮询 是否有需要结束的订单
  requestSetMyRecipient: function () {
    var _uid = wx.getStorageSync("userInfo").userInfo.uid;
    wx.request({
      url: "https://boxapi.supergk.com/server/user/insure_service_end_list",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      data: util.json2Form({ uid: _uid }),
      success: function (res) {
        console.log(res);
        if (res.data.code == 0) {
          console.log(res.data.msg);
          if(res.data.data){
            var _service_id = res.data.data.id;
            wx.showModal({
              title: '快递员服务完毕',
              content: '您的快递员表示已经完成了本次服务，为了避免不必要的损失，请您核实后点击确认。',
              cancelText:"拒绝",
              confirmText:"确认",
              confirmColor:"#3b8cdd",
              cancelColor:"#858585",
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                  const requestSetMyRecipient = wx.request({
                    url: "https://boxapi.supergk.com/server/user/insure_service_end",
                    header: {
                      "Content-Type": "application/x-www-form-urlencoded"
                    },
                    method: "POST",
                    data: util.json2Form({ uid: _uid, service_id: _service_id}),
                    success: function (res) {
                      console.log(res);
                      if (res.data.code == 0) {
                        console.log(res.data.msg);
                        that.data.orderStatus.data.state = 1
                        that.setData({
                          // hasOrderUnderway: "0",
                          orderStatus: that.data.orderStatus,
                        })
                        wx.showToast({
                          title: '服务完毕',
                          icon:"success"
                        })
                      } else {
                        console.log(res.data.msg)
                      }
                    }
                  })
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
            wx.navigateTo({
              url: '../endServer/endServer?server_id=' + _service_id,
            })
          }
        } else {
          console.log(res.data.msg)
        }
      }
    })
  },


  // 跳转到进行中的订单
  movetoOrderUnderway: function () {
    wx.navigateTo({
      url: '../my/orderUnderway/orderUnderway',
    })
  }

})
var that;